package com.mgm.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.mgm.annotation.Authorization;
import com.mgm.constant.GobalConstant;
import com.mgm.result.IMessage;
import com.mgm.user.service.UserService;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
	
	private static Logger logger =LoggerFactory.getLogger(AuthorizationInterceptor.class);

    @Autowired
    private UserService userManager;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		// 从header中得到token
		String token = request.getHeader(GobalConstant.AUTHORIZATION);
		logger.debug("Get token from header : {}", token);

		IMessage msg = userManager.checkToken(token);

		if (!msg.isSuccess()) {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/x-json;charset=UTF-8");
            //解决跨域问题 
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
            JSONObject jsObject =(JSONObject) JSONObject.toJSON(msg);
            response.getWriter().write(jsObject.toString());
			response.setStatus(msg.getStatus()); //HttpServletResponse.SC_UNAUTHORIZED
			return false;
		}
		
		//如果验证token失败，并且方法注明了Authorization，返回401错误
        if (method.getAnnotation(Authorization.class) != null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

		return true;
	}
}